<template>
  <div class="card-out-container line-set-station">
    <a-spin :spinning="loading">
      <a-form ref="stationForm" :model="stationList">
        <CustomTable :operateMargin="true" storeTableName="stationTable" bordered size="small" :data-source="stationList" :columns="columns" :pagination="false" rowKey="id" :rowSelection="isEnvLocal ?null:{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, getCheckboxProps: checkboxProps,fixed: 'left'}" :scroll="{y: 'calc(100vh - 300px)'}" class="line-set-station-table" @change="handleTableChange1" tableColumnsSort="">
          <template #operateLeft>
            <div class="operate-left">
              <a-button v-if="isEnvLocal" type="primary" @click="syncData(syncDataAry)">{{ $t('common.sync') }}</a-button>
              <span v-else>
                <a-button type="primary" @click="getWaterThreeList();modalDo({},'addForm',false)">{{ $t('common.add') }}</a-button>
                <span v-if="this.isEdit">
                  <a-button type="warning" ghost :disabled="!this.selectedRowKeys.length" @click="delVersionList()">{{ $t('common.delMore') }}</a-button>
                  <a-button type="primary" @click="saveData">{{ $t('common.save') }}</a-button>
                  <a-button type="warning" ghost @click="this.isEdit=false;this.loadData();">{{ $t('common.cancel') }}</a-button>
                </span>
                <span v-else>
                  <a-button type="primary" ghost @click="this.isEdit=true;">{{$t('other.editBatch')}}</a-button>
                  <a-button type="warning" ghost :disabled="!this.selectedRowKeys.length" @click="delVersionList()">{{ $t('common.delMore') }}</a-button>
                </span>
              </span>
            </div>
          </template>
          <template #operateRight>
            <div class="slot-operate-right">
              <a-select v-model:value="this.hangerLineId" :placeholder="$t('deviceManage.pleaseSelectWaterLineNo')" enter-button @change="loadData">
                <a-select-option v-for="item in this.waterThreeList" :key="item" :value="item.id">{{ item.lineNo }}</a-select-option>
              </a-select>
            </div>
          </template>

          <template #headerCell="{ scope }">
            <template v-for="(item , index) in requiredHeader" :key="index">
              <template v-if="scope.column.key === item.value">
                <span class="text-red">*</span>{{item.key}}
              </template>
            </template>
          </template>
          <template #bodyCell="{ scope }">
            <template v-if="scope.column.key === 'stationNo'">
              {{getFieldText(waterThreeList,scope.record.hangerLineId,'id','lineNo')}}-{{scope.record.stationNo}}
            </template>
            <template v-if="scope.column.key === 'masterTrackId'">
              <a-select v-model:value="scope.record.masterTrackId" :placeholder="$t('common.pleaseSelect')" v-if="this.isEdit  || scope.record.editStatue" style="width: 100%;">
                <a-select-option v-for="item in masterTrackList" :key="item" :value="item.id">{{ item.masterTrackNo }}</a-select-option>
              </a-select>
              <span v-else>{{getFieldText(masterTrackList,scope.record.masterTrackId,'id','masterTrackNo')}}</span>
            </template>
            <template v-if="scope.column.key === 'lineModel'">
              <a-form-item :name="[scope.index, 'lineModel']" :rules="{ required: true, message: $t('common.pleaseSelect')}" v-if="this.isEdit  || scope.record.editStatue">
                <a-select v-model:value="scope.record.lineModel" :options="lineModelList" :placeholder="$t('common.pleaseSelect')" v-if="this.isEdit  || scope.record.editStatue"></a-select>
              </a-form-item>
              <span v-else>{{ getText(lineModelList, scope.record.lineModel, 'value') }}</span>
            </template>
            <template v-if="scope.column.key === 'direction'">
              <a-select v-model:value="scope.record.direction" :options="this.directionArray" :placeholder="$t('common.pleaseSelect')" v-if="this.isEdit  || scope.record.editStatue" style="width: 100%;"></a-select>
              <span v-else>{{ getText(directionArray, scope.record.direction, 'value') }} </span>
            </template>
            <template v-if="scope.column.key === 'inStationOffset1'">
              <a-form-item :name="[scope.index, 'inStationOffset1']" :rules="[{ required: true, message: $t('other.pleaseInputInBoundFirst')}, { pattern: /^\d+(\.\d{1,3})?$/, message: $t('other.pleaseInputTrueFormatDecmal'),trigger: 'change' }]" v-if="this.isEdit  || scope.record.editStatue">
                <a-input-number v-model:value="scope.record.inStationOffset1" :placeholder="$t('other.pleaseInputInBoundFirst')" :min="0" />
              </a-form-item>
              <span v-else>{{ scope.record.inStationOffset1 }}</span>
            </template>
            <template v-if="scope.column.key === 'inStationOffset2'">
              <a-form-item :name="[scope.index, 'inStationOffset2']" :rules="[{ required: true, message: $t('other.pleaseInputInBoundSec')}, { pattern: /^\d+(\.\d{1,3})?$/, message: $t('other.pleaseInputTrueFormatDecmal'),trigger: 'change' }]" v-if="this.isEdit  || scope.record.editStatue">
                <a-input-number v-model:value="scope.record.inStationOffset2" :placeholder="$t('other.pleaseInputInBoundSec')" :min="0" />
              </a-form-item>
              <span v-else>{{ scope.record.inStationOffset2 }}</span>
            </template>
            <template v-if="scope.column.key === 'inStationOffset3'">
              <a-form-item :name="[scope.index, 'inStationOffset3']" :rules="[{ required: true, message: $t('other.pleaseInputinBoundThr')}, { pattern: /^\d+(\.\d{1,3})?$/, message: $t('other.pleaseInputTrueFormatDecmal') }]" v-if="this.isEdit  || scope.record.editStatue">
                <a-input-number v-model:value="scope.record.inStationOffset3" :placeholder="$t('other.pleaseInputinBoundThr')" :min="0" />
              </a-form-item>
              <span v-else>{{ scope.record.inStationOffset3 }}</span>
            </template>
            <template v-if="scope.column.key === 'outStationOffset'">
              <a-form-item :name="[scope.index, 'outStationOffset']" :rules="[{ required: true, message: $t('other.pleaseInputOutBoundOffset')}, { pattern: /^\d+(\.\d{1,3})?$/, message: $t('other.pleaseInputTrueFormatDecmal') }]" v-if="this.isEdit  || scope.record.editStatue">
                <a-input-number v-model:value="scope.record.outStationOffset" :placeholder="$t('other.pleaseInputOutBoundOffset')" :min="0" />
              </a-form-item>
              <span v-else>{{ scope.record.outStationOffset }}</span>
            </template>
            <template v-if="scope.column.key === 'isBridge'">
              <a-checkbox v-model:checked="scope.record.isBridge" v-if="this.isEdit  || scope.record.editStatue"></a-checkbox>
              <a-checkbox v-model:checked="scope.record.isBridge" v-else disabled></a-checkbox>
            </template>
            <template v-if="scope.column.key === 'belowLinkage'">
              <a-checkbox v-model:checked="scope.record.belowLinkage" v-if="this.isEdit  || scope.record.editStatue"></a-checkbox>
              <a-checkbox v-model:checked="scope.record.belowLinkage" v-else disabled></a-checkbox>
            </template>
            <template v-if="scope.column.key === 'loadDetect'">
              <a-checkbox v-model:checked="scope.record.loadDetect" v-if="this.isEdit  || scope.record.editStatue"></a-checkbox>
              <a-checkbox v-model:checked="scope.record.loadDetect" v-else disabled></a-checkbox>
            </template>
            <template v-if="scope.column.key === 'status'">
              <a-checkbox v-model:checked="scope.record.status" v-if="this.isEdit  || scope.record.editStatue"></a-checkbox>
              <a-checkbox v-model:checked="scope.record.status" v-else disabled></a-checkbox>
            </template>
            <template v-if="scope.column.key === 'motorDelay'">
              <a-form-item :name="[scope.index, 'motorDelay']" :rules="{ required: true, message: $t('other.pleaseInputMotorDelay')}" v-if="this.isEdit  || scope.record.editStatue">
                <a-input-number v-model:value="scope.record.motorDelay" :placeholder="$t('other.pleaseInputMotorDelay')" :min="0" />
              </a-form-item>
              <span v-else>{{ scope.record.motorDelay }}</span>
            </template>
            <template v-if="scope.column.key === 'outBufferAmount'">
              <a-form-item :name="[scope.index, 'outBufferAmount']" :rules="{ required: true, message: $t('other.pleaseInputBuffer')}" v-if="this.isEdit  || scope.record.editStatue">
                <a-input-number v-model:value="scope.record.outBufferAmount" :placeholder="$t('other.pleaseInputBuffer')" :min="0" />
              </a-form-item>
              <span v-else>{{ scope.record.outBufferAmount }}</span>
            </template>
            <template v-if="scope.column.key === 'inStationRetentionTime'">
              <a-form-item :name="[scope.index, 'inStationRetentionTime']" :rules="{ required: true, message: $t('other.pleaseInputInBoundKeepTime')}" v-if="this.isEdit  || scope.record.editStatue">
                <a-input-number v-model:value="scope.record.inStationRetentionTime" :placeholder="$t('other.pleaseInputInBoundKeepTime')" :min="0" />
              </a-form-item>
              <span v-else>{{ scope.record.inStationRetentionTime }}</span>
            </template>
            <template v-if="scope.column.key === 'lowerDelayTime'">
              <a-form-item :name="[scope.index, 'lowerDelayTime']" :rules="{ required: true, message: $t('other.pleaseInputDeferralTime') }" v-if="this.isEdit  || scope.record.editStatue">
                <a-input-number v-model:value="scope.record.lowerDelayTime" :placeholder="$t('other.pleaseInputDeferralTime')" :min="0" />
              </a-form-item>
              <span v-else>{{ scope.record.lowerDelayTime }}</span>
            </template>
            <template v-if="scope.column.key === 'outStationAntiShakeType'">
              <!--          <a-select v-model:value="scope.record.outStationAntiShakeType" :options="this.outStationAntiShakeTypeArray" :placeholder="$t('common.pleaseSelect')" v-if="this.isEdit  || scope.record.editStatue" style="width: 100%;">-->
              <!--          </a-select>-->
              <a-select v-model:value="scope.record.outStationAntiShakeType" :placeholder="$t('common.pleaseSelect')" v-if="this.isEdit  || scope.record.editStatue" style="width: 100%;">
                <a-select-option v-for="(value,key) in this.outStationAntiShakeTypeArray" :key="key" :value="value.value">
                  {{ value.label }}</a-select-option>
              </a-select>
              <span v-else>{{ getText(outStationAntiShakeTypeArray, scope.record.outStationAntiShakeType, 'value') }} </span>
            </template>
            <template v-if="scope.column.key === 'outStationAntiShakeTime'">
              <a-form-item :name="[scope.index, 'outStationAntiShakeTime']" :rules="{ required: true, message: $t('other.pleaseInputOutputAntiTime')}" v-if="this.isEdit  || scope.record.editStatue">
                <a-input-number v-model:value="scope.record.outStationAntiShakeTime" :placeholder="$t('other.pleaseInputOutputAntiTime')" :min="0" />
              </a-form-item>
              <span v-else>{{ scope.record.outStationAntiShakeTime }}</span>
            </template>
            <template v-if="scope.column.key === 'coatHangerNumberInTrack'">
              <a-form-item :name="[scope.index, 'coatHangerNumberInTrack']" :rules="{ required: true, message: $t('other.pleaseInputTrackCapacity') }" v-if="this.isEdit  || scope.record.editStatue">
                <a-input-number v-model:value="scope.record.coatHangerNumberInTrack" :placeholder="$t('other.pleaseInputTrackCapacity')" :min="0" />
              </a-form-item>
              <span v-else>{{ scope.record.coatHangerNumberInTrack }}</span>
            </template>
            <template v-if="scope.column.key === 'capacity'">
              <a-form-item :name="[scope.index, 'capacity']" :rules="{ required: true, message: $t('other.pleaseInputStationCapacity')}" v-if="this.isEdit  || scope.record.editStatue">
                <a-input-number v-model:value="scope.record.capacity" :placeholder="$t('other.pleaseInputStationCapacity')" :min="0" />
              </a-form-item>
              <span v-else>{{ scope.record.capacity }}</span>
            </template>
            <template v-if="scope.column.key === 'role'">
              <a-form-item :name="[scope.index, 'role']" :rules="{ required: true, message: $t('other.pleaseSelectRole')}" v-if="this.isEdit  || scope.record.editStatue">
                <a-select v-model:value="scope.record.role" :options="roleList" :placeholder="$t('other.pleaseSelectRole')" v-if="this.isEdit  || scope.record.editStatue"></a-select>
              </a-form-item>
              <span v-else>{{ getText(roleList, scope.record.role, 'value') }}</span>
            </template>
            <template v-if="scope.column.key === 'remark'">
              <a-input v-model:value.trim="scope.record.remark" v-if="this.isEdit || scope.record.editStatue" />
              <span v-else>{{ scope.record.remark }}</span>
            </template>
            <template v-if="scope.column.key === 'operate'">
              <span v-if="scope.record.editStatue || this.isEdit" class="table-operate-container">
                <a-button type="link" class="primary-link" @click="savetableStatue(scope.record)">{{ $t('common.save') }}</a-button>
                <a-divider type="vertical" />
                <a-button type="link" class="primary-link" @click="this.isEdit=false;this.loadData();">{{ $t('common.cancel') }}</a-button>
              </span>
              <span v-else>
                <a-button type="link" class="primary-link" @click="scope.record.editStatue = true">{{ $t('common.editor') }}</a-button>
              </span>
              <a-divider type="vertical" />
              <a-button type="link" :disabled="scope.record.status" danger @click="delVersion(scope.record,scope.index)">{{ $t('common.del') }}</a-button>
            </template>
          </template>
        </CustomTable>

      </a-form>

      <add-dialog ref="addForm" @backValues="handleOk"></add-dialog>
      <edit-dialog ref="modalForm" @backValues="handleOk"></edit-dialog>
      <SyncDataModal ref="syncDataModalRef" />
    </a-spin>
  </div>
</template>
<script>
import { ListMixinPm } from '@/mixin/listMixinPm.js'
import { getText, getFieldText, toLineName } from '@/utils'
import EditDialog from './modules/editDialog.vue'
import AddDialog from './modules/addDialog.vue'
import axios from '@/utils/request'
import { cloneDeep, isEmpty } from "lodash";
import { message } from "ant-design-vue";
import CustomTable from '@/components/commonTable/customTable.vue'
import SyncDataModal from '@/components/syncModal/syncDataModal.vue'
import { url, localColumns, normalColumns, directionArray, outStationAntiShakeTypeArray, roleList, requiredHeader, lineModelList } from './modules/config'
export default {
  name: 'hangLineStation',
  mixins: [ListMixinPm],
  components: {
    AddDialog,
    EditDialog,
    CustomTable,
    SyncDataModal
  },
  data () {
    return {
      url,
      columns: [],
      lineModelList: lineModelList,
      requiredHeader,
      directionArray,
      outStationAntiShakeTypeArray,
      roleList,
      waterThreeList: [],
      waterList: [],
      groupList: [],
      masterTrackList: [],
      stationList: [],
      hangerLineId: undefined,
      stepNum: 0,
      isEdit: false,
      loading: false,
      isorter1: {},
      syncDataAry: [
        { syncIotCloudDataType: 'ihs:device:station' },
        { syncIotCloudDataType: 'ihs:device:masterTrack' },
        { syncIotCloudDataType: 'ihs:device:hangerLine' },
        { syncIotCloudDataType: 'ihs:device:hangerLinePushRod' },
        { syncIotCloudDataType: 'ihs:device:hangerLineGroup' }
      ],
    }
  },
  async created () {
    this.columns = this.isEnvLocal ? localColumns : normalColumns
    await this.getWaterThreeList();
    await this.getGroupList();
    this.loadData();
  },
  methods: {
    checkboxProps (record) {
      return {
        disabled: record.status,
        name: `${record.status}`
      }
    },
    getText,
    getFieldText,
    async saveData () {
      await this.$refs.stationForm.validateFields();
      let formData = cloneDeep(this.stationList)
      let ruleValue = 1;

      formData && formData.forEach(item=>{
        let { inStationOffset1, inStationOffset2, inStationOffset3, outStationOffset } = item
        item.isBridge = item.isBridge ? 1 : 0;
        item.belowLinkage = item.belowLinkage ? 1 : 0;
        item.loadDetect = item.loadDetect ? 1 : 0;
        item.status = item.status ? 0 : 1;
        item.inStationOffset1 = inStationOffset1 * 1000
        item.inStationOffset2 = inStationOffset2 * 1000
        item.inStationOffset3 = inStationOffset3 * 1000
        item.outStationOffset = outStationOffset * 1000
        if (item.inStationOffset1 === null || item.inStationOffset2 === null || item.inStationOffset3 === null || item.outStationOffset === null || item.motorDelay === null || item.coatHangerNumberInTrack === null || item.role === null) {
          ruleValue = 0;
        }
      })

      if (ruleValue) {
        this.loading = true
        try {
          const res = await axios.postAction(this.url.update, formData)
          if (res.success) {
            message.success(this.$t('common.doSuccess'))
            this.isEdit = false;
            this.loading = false;
            this.loadData();
          } else {
            this.loading = false;
            message.error(this.$t('common.doError'))
          }
        } catch (err) {
          this.isEdit = false;
          this.loading = false;
          this.loadData();
          // console.log('0000000', err);
        }
      } else {
        this.loading = false;
        message.error(this.$t('other.mandatoryNull'));
      }
    },
    async savetableStatue (value) {
      const newValue = [];
      newValue.push(value)
      await this.$refs.stationForm.validateFields();
      let formData = cloneDeep(newValue)
      let ruleValue = 1;
      formData && formData.forEach(item=>{
        let { inStationOffset1, inStationOffset2, inStationOffset3, outStationOffset } = item
        item.isBridge = item.isBridge ? 1 : 0;
        item.belowLinkage = item.belowLinkage ? 1 : 0;
        item.loadDetect = item.loadDetect ? 1 : 0;
        item.status = item.status ? 0 : 1;
        item.outStationRod = item.inStationRod
        item.inStationOffset1 = inStationOffset1 * 1000
        item.inStationOffset2 = inStationOffset2 * 1000
        item.inStationOffset3 = inStationOffset3 * 1000
        item.outStationOffset = outStationOffset * 1000
        if (item.inStationOffset1 === null || item.inStationOffset2 === null || item.inStationOffset3 === null || item.outStationOffset === null || item.motorDelay === null || item.coatHangerNumberInTrack === null || item.role === null) {
          ruleValue = 0;
        }
      })

      if (ruleValue) {
        this.loading = true
        try {
          const res = await axios.postAction(this.url.update, formData)
          if (res.success) {
            message.success(this.$t('common.doSuccess'))
            this.isEdit = false;
            this.loading = false;
            this.loadData();
          } else {
            this.isEdit = false
            this.loading = false;
            this.loadData();
          }
        } catch (err) {
          this.isEdit = false;
          this.loading = false;
          this.loadData();
        }
      } else {
        this.isEdit = false
        this.loading = false;
        message.error(this.$t('other.mandatoryNull'));
      }
    },
    async handleOk (value) {
      if (value) {
        this.hangerLineId = value.hangerLineId;
        this.stepNum = 0;
        await this.loadData()
        this.$refs.modalForm.close()

        let tempForm = JSON.parse(JSON.stringify(this.stationList));
        for (let i = 0; i < value.num; i++) {
          const newStationObj = {
            "hangerLineId": 0,
            "masterTrackId": 0,
            "stationNo": 0,
            "direction": 0,
            "lineModel": 1,
            "inStationOffset1": 0,
            "inStationOffset2": 0,
            "inStationOffset3": 0,
            "outStationOffset": 3.07,
            "isBridge": 0,
            "belowLinkage": 0,
            "loadDetect": 0,
            "motorDelay": 200,
            "outBufferAmount": 2,
            "inStationRetentionTime": 2300,
            "lowerDelayTime": 100,
            "outStationAntiShakeType": 0,
            "outStationAntiShakeTime": 300,
            "coatHangerNumberInTrack": 15,
            "capacity": 25,
            "role": '3',
            "remark": "",
            "status": 1
          }
          newStationObj.hangerLineId = value.hangerLineId;
          newStationObj.masterTrackId = value.masterTrackId;
          newStationObj.stationNo = this.stepNum + 1 + i;
          tempForm.push(newStationObj);
        }
        this.stationList = tempForm;
        this.isEdit = true;
      }
      // console.log(this.stepNum)
    },

    async getWaterThreeList () {
      const res = await axios.postAction(this.url.waterThreeUrl)
      if (res.success) {
        this.waterThreeList = res.data
        this.hangerLineId = res.data.length ? res.data[0].id : undefined;
        res.data.forEach(item => {
          if (item.id === this.hangerLineId) {
            this.masterTrackList = item.masterTrackList;
          }
        })
      }
    },
    async getGroupList () {
      const res = await axios.postAction(this.url.groupUrl)
      if (res.success) {
        res.data.forEach(item => {
          item.label = item.masterTrackNo
          item.value = item.id
        })
        this.waterList = res.data
        this.groupList = res.data
      }
    },
    async getTrackList () {
      this.waterThreeList.forEach(item => {
        if (item.id === this.hangerLineId) {
          this.masterTrackList = item.masterTrackList;
        }
      })
    },

    handleTableChange1 (pagination, filters, sorter) {
      if (Object.keys(sorter).length > 0) {
        this.isorter1.field = sorter.order ? toLineName(sorter.field) : ''
        this.isorter1.order = sorter.order ? sorter.order == 'ascend' ? 'asc' : 'desc' : ''
      }
      this.ipagination = Object.assign(this.ipagination, pagination)
      this.loadData()
    },

    async loadData () {
      if (this.hangerLineId !== "" && this.hangerLineId != null) {
        const res = await axios.postAction(this.url.stationUrl, {
          pageNo: 1,
          pageSize: 999999,
          hangerLineId: this.hangerLineId,
          sortingFields: this.isorter1.field ? [this.isorter1] : null
        })
        if (res.success) {
          if (res.data.list.length > 0) {
            res.data.list.forEach(item => {
              item.isBridge = item.isBridge == 1 ? true : false;
              item.belowLinkage = item.belowLinkage == 1 ? true : false;
              item.loadDetect = item.loadDetect == 1 ? true : false;
              item.status = item.status == 1 ? false : true;
              item.inStationOffset1 = ((item.inStationOffset1 || 0) / 1000).toFixed(3) / 1
              item.inStationOffset2 = ((item.inStationOffset2 || 0) / 1000).toFixed(3) / 1
              item.inStationOffset3 = ((item.inStationOffset3 || 0) / 1000).toFixed(3) / 1
              item.outStationOffset = ((item.outStationOffset || 0) / 1000).toFixed(3) / 1
            })
            const sortValue = cloneDeep(res.data.list)
            sortValue.sort((a, b) => a.stationNo - b.stationNo); // 获取最大的座位号
            this.stepNum = sortValue[sortValue.length - 1].stationNo; //获取res.data数组的最后一位
          }
          this.stationList = res.data.list;
          this.getTrackList();
        }
      }
    },
    //删除 行元素
    async delVersion (record ) {
      if (!isEmpty(record.id)) {
        let delArr = [];
        delArr.push(record.id);
        this.confirmChangeStatus('/api/device/station/delete',delArr, null, '提示', 'deleteAction')
      }
    },
    //删除 多行元素
    async delVersionList () {
      // console.log('this.selectedRowKeys', this.selectedRowKeys)
      if (!isEmpty(this.selectedRowKeys) && !isEmpty(this.stationList)) {
        this.confirmChangeStatus('/api/device/station/delete',this.selectedRowKeys, null, '提示', 'deleteAction')
      }

    },

    initModalSelectOptions () {
      return {
        waterThreeList: this.waterThreeList,
        waterList: this.waterList,
        groupList: this.groupList,
        stationList: this.stationList,
        masterTrackList: this.masterTrackList
      }
    }
  },
}
</script>
<style lang="less" scoped>
.ant-form-item {
  margin-bottom: 0px;
}
</style>